<template>
  <div>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="450px" :before-close="close">

      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" >
        <el-form-item label="上级菜单:">
          <select-tree :options="options" :props="prop" @getValue="getValue" :value="value" ref="tree"></select-tree>
        </el-form-item>
        <el-form-item label="菜单名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="菜单地址:" prop="url">
          <el-input v-model="form.url" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="权限:" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in optionsp" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图标:" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="排序:" prop="idx1">
           <el-input-number v-model="form.idx1" style="width: 100%;"  controls-position="right" @change="handleChange" :min="1"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="qx">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>

    </el-dialog>

    <el-row>
      <el-col style="margin-bottom: 20px;">
        <el-button-group>
          <el-button type="info" size="small" icon="el-icon-plus" @click="add">新增</el-button>
          <el-button type="info" size="small" icon="el-icon-edit" @click="edit" :disabled="!row">修改</el-button>
          <el-button type="info" size="small" icon="el-icon-delete" @click="del" :disabled="!row">删除</el-button>
          <el-button type="infor" size="small" icon="el-icon-refresh" @click="refresh">刷新</el-button>
        </el-button-group>
      </el-col>
    </el-row>
    <el-table  :data="tableData" highlight-current-row ref="table" style="width: 100%;  " row-key="id" border
      @current-change="changeRow"  :tree-props="{children: 'nodes'}">
      <el-table-column prop="name" label="菜单名称">
      </el-table-column>
      <el-table-column prop="url" label="地址">
      </el-table-column>
      <el-table-column prop="Permission.name" label="权限">
      </el-table-column>
      <el-table-column prop="icon" label="图标">
      </el-table-column>
      <el-table-column prop="idx1" label="排序">
      </el-table-column>
    </el-table>
  </div>

</template>

<script>
  import selectTree from '../../components/selectTree.vue'
  export default {
    components: {
      selectTree
    },
    data() {
      var name= (rule, value, callback) => {
         if (value === ''||value===null||value===undefined) {
           callback(new Error('请输入'));
         } else {
           let re=/^[\u4E00-\u9FA5A-Za-z0-9]+$/;
           if (!re.test(value)) {
             callback(new Error('请输入中文、英文、数字但不包括下划线等符号!'));
           }else{
             let res=/^.{2,20}$/;
             if (!res.test(value)) {
               callback(new Error('菜单名称至少有2个字符，至多个字符！'));
             }
           }
           callback();
         }
       };
      return {
        tableData: undefined,
        row: undefined,
        dialogVisible: false,
        form: {
          roleId: 1,
        },
        options: undefined,
        options2: [],
        pname: '',
        prop: {
          value: 'id',
          label: "name",
          children: "nodes"
        },
        value: '',
        optionsp: '',
        rules: {

          name: [{
            required:true,
            validator: name,
            trigger: 'blur',
          }],
          url: [{
            required:true,
            message:'请输入地址',
            trigger: 'blur',
          }],
          idx1: [{
            required:true,
            message:'请输入',
            trigger: 'blur',
          }],
          roleId: [{
            required:true,
            message:'请输入',
            trigger: 'blur',
          }],
        }
      }
    },
    methods: {
      handleChange(val){
        if(val==undefined||val==null){
          this.form.idx1=1;
        }
      },
      close() {
        this.empty();
      },
      changeRow(row) {
        this.row = row;
      },
      getValue(value) {
        this.form.parentId = value;
      },
      add() {
        if (this.row) {
          this.form = {
            "parentId": this.row.id
          }
        }
        this.value = this.form.parentId
        this.dialogVisible = true
        this.options = this.tableData;
      },
      edit() {
        this.dialogVisible = true
        this.form = deepClone1(this.row)
        this.form.roleId = this.row.Permission.id
        this.value = this.form.parentId
        let opts = deepClone1(this.tableData)
        this.options = dataTree(opts, this.row)
      },
      del() {
        this.$confirm('确认删除？').then(_ => {
          if (this.row.parentId == null) {
            this.row.parentId = 0
          }
          this.$ajax.post('menu/delete', this.row).then(res => {
            let result = res.data;
            if (result.success) {
              this.empty();
              this.updateTable();
              this.$notify({
                type: 'success',
                title: '提示',
                message: '数据删除成功',
                position: 'bottom-right'
              });
            }

          }).catch(errors => {})
        })
      },
      refresh(row) {
        this.updateTable()
        this.$refs.table.setCurrentRow(row);
        this.row = null;
        this.$notify({
          type: 'success',
          title: '提示',
          message: '刷新成功',
          position: 'bottom-right'
        });
      },
      qx() {
        this.empty();
      },
      empty() {
        this.dialogVisible = false;
        this.$refs.tree.clearHandle();
        this.options = undefined
        this.form = {}
        this.$refs.table.setCurrentRow()
        this.value = undefined
      },
      save() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            if(!this.form.parentId){
              this.form.parentId = '';
            }
            this.$ajax.post('menu/save', this.form).then(res => {
              let result = res.data;
              if (result.success) {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                });
                this.empty();
                this.updateTable();
              }
            }).catch(error => {
              this.$message({
                message: '保存失败',
                type: 'warning'
              });
            })
          }
        })
      },
      updateTable() {
        this.$ajax.post('menu/combotree', {}).then(res => {

          this.tableData = res.data
          this.options=res.data
           this.pname=res.data[0].Permission.name
        }),
        this.$ajax.post('permission/page',{}).then(res=>{
          this.optionsp=res.data.data.rows
        })
      }
    },
    mounted() {
      this.updateTable();
    }
  }

  function dataTree(opts, row) {
    if (opts != null) {
      for (let Key in opts) {
        let o = opts[Key];

        if (o.id == row.id) {
          opts.splice(Key, 1);
          return opts;
        } else {
          dataTree(o.nodes, row);
        }
      }

    }
    return opts;
  }

  function deepClone1(obj) {
    //判断拷贝的要进行深拷贝的是数组还是对象，是数组的话进行数组拷贝，对象的话进行对象拷贝
    var objClone = Array.isArray(obj) ? [] : {};
    //进行深拷贝的不能为空，并且是对象或者是
    if (obj && typeof obj === "object") {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (obj[key] && typeof obj[key] === "object") {
            objClone[key] = deepClone1(obj[key]);
          } else {
            objClone[key] = obj[key];
          }
        }
      }
    }
    return objClone;
  }
</script>

<style>
  .card {
    min-height: calc(100% - 5px);
  }
</style>
